
#include "Debug.h"
#include <sstream>
#include <string>
#include <stdlib.h>
#include <sys/stat.h>
//#include <libpq-fe.h>
#include <map>
#include <string.h>
#include <glib.h>
#include <assert.h>
#include "config.h"
#include "define.h"
#include "CobwebMql.h"

using namespace std;

extern "C" {
  bool nidmConsInit(char *consumer, const char* conf);
  int nidmConsFriends(char *user, GHashTable *frs);
  int nidmConsUpdate(char *user, long expire, GHashTable *frs);
  void nidmConsShutdown();
  void nidmConsFlush(char *consumer);
};

CobWebMQL *pDB = NULL;
//static int g_expire = 86400*3;
bool nidmConsInit(char *consumer, const char* conf)
{
        struct stat st;
        if (lstat(conf, &st) != 0)
        {
                ERRO<<":"<<conf<<" is not exist!"<<endl;
                return false;
        }
        Configure cfg;
        map <string, string > g_Confs;
        g_Confs = cfg.LoadConfInfo(conf);
        cfg.Print();
        if(g_Confs.size() <= 0)
        {
                cerr<<"error to explain conf :"<< conf<<endl;
                return true;
        }
        map <string, string >::iterator iter;
        string dbhost, dbuser, dbpass, dbname;
/*
        if (g_Confs.find("dbhost") != g_Confs.end())
                dbhost = g_Confs["dbhost"];
        if (g_Confs.find("dbuser") != g_Confs.end())
                dbuser = g_Confs["dbuser"];
        if (g_Confs.find("dbpass") != g_Confs.end())
                dbpass = g_Confs["dbpass"];
        if (g_Confs.find("dbname") != g_Confs.end())
		dbname = g_Confs["dbname"];
        string dbport = "5432";
        if (g_Confs.find("dbport") != g_Confs.end())
		dbport = g_Confs["dbport"];
	g_db = PQsetdbLogin(dbhost.c_str(), dbport.c_str(), NULL, NULL, dbname.c_str(), dbuser.c_str(), dbpass.c_str());

	if(PQstatus(g_db) != CONNECTION_OK)
	{
		ERRO << PQerrorMessage(g_db) << endl;
		PQfinish( g_db);
		g_db = NULL;
                return false;
	}
*/
        string smax, dbfile;
        if (g_Confs.find("maxtable") != g_Confs.end())
                smax = g_Confs["maxtable"];

        int imaxt = atoi(smax.c_str());
        if(imaxt < 1)
           imaxt = 1;

        if (g_Confs.find("dbhost") != g_Confs.end())
                dbhost = g_Confs["dbhost"];
        if (g_Confs.find("dbuser") != g_Confs.end())
                dbuser = g_Confs["dbuser"];
        if (g_Confs.find("dbpass") != g_Confs.end())
                dbpass = g_Confs["dbpass"];
        if (g_Confs.find("dbname") != g_Confs.end())
		dbname = g_Confs["dbname"];


        pDB = new CobWebMQL(dbhost.c_str(), dbname.c_str(), dbuser.c_str(), dbpass.c_str(), imaxt);
        if(!pDB->Initialize())
             return false;
/*
        string s; 
        if (g_Confs.find("uexpire") != g_Confs.end())
                s = g_Confs["uexpire"];
        g_expire = atoi(s.c_str()); 
*/
        return true;
}

int nidmConsFriends(char * user, GHashTable *frs)
{
   string val, name;
   long  expire = 0;
   int ic = pDB->Fetch(user, name , val, expire);
   if(ic == -1)
          return -1;
   if(val.length()<= 0)
   {
	   if(name.length() > 0)
		   return 1;
	   DEBUG1("fetch from DB, no data!");
	   return 0;
   } 
   // val = stamp:name;nid:name;nid:name;nid:name
   char **columns = g_strsplit(val.c_str(), ";", -1);
   int columns_num =  g_strv_length(columns);
   if(columns_num < 1)
   {
           DEBUG1("data is error!");
	   g_strfreev(columns);
	   return 1;
   }
  
   FObject *uself = new FObject(user, 1, (char *)name.c_str()) ;
   g_hash_table_insert(frs, g_strdup(user), uself);

   for(int i=0; i< columns_num ; i++ )
   { // nid:name:kid 
	   const char *p = columns[i];
	   char sid[2048];
	   char *q = sid;
	   bool bfind = false;
	   while(*p)
	   {
		   if(*p != ':')
			   *q++=*p;
		   else
		   {
			   *q ='\0';
			   ++p;
			   bfind = true;
			   break;
		   }
		   ++p;
	   }

	   if(!bfind || p == NULL || strlen(sid) <= 0)
		   return 0;

   DEBUG4("ID=", sid[0], "; value=", p);
	   FObject *uself = new FObject((char *)sid, 1, (char *)p ) ;
	   g_hash_table_insert(frs, g_strdup(sid), uself);
	 //  g_strfreev(scolumns);
   }
   g_strfreev(columns);
   DEBUG2("YES, Data size = ", columns);
   return  columns_num;
}

int nidmConsUpdate(char * user, long lt,  GHashTable *frs)
{
	assert(user != NULL);
        return 0;
}

void nidmConsShutdown()
{
        if(pDB != NULL)
           delete pDB; 
 // Do whatever to close/flush/sync the consumer's work before exit...
  //   delete gx_TxLog;
}

void nidmConsFlush(char * consumer)
{
  // If this consumer keeps statistics or writes to a tx log, then
  // flush the statistics here, otherwise do nothing.
}


